/**
 author: chengzheng
 date: 2018/1/4
 email: 13120207061@163.com
 */
const phantom = require('phantom');
const logger = require("../../logger");
module.exports.request = async function (options) {
    var phInstance = null;
    var sitePage = null;
    var retryLimit = 1;
    await phantom.create(['--ignore-ssl-errors=yes', '--load-images=no'], {
        phantomPath: './phantom'
    })
        .then(instance => {
            phInstance = instance;
            return instance.createPage();
        })
        .then(page => {
            sitePage = page;
        })
        .catch(error => {
            logger.fatal(`err occur construct sitePage,message is [${error.toString()}]`)
            console.log(error);
            phInstance.exit();
        });


    await sitePage.on("onResourceRequested", function (requestData) {
        console.info('Requesting', requestData.url)
    });

    sitePage.setting('javascriptEnabled').then(function (value) {
        expect(value).toEqual(true);
    });

    if (!!options.userAgent) {
        sitePage.setting("userAgent", options.userAgent);
    }


    //重试次数
    if (!!options.retryLimit) {
        retryLimit = option.retryLimit;
    }

    sitePage.property('plainText').then(function (content) {
        logger.info(content);
    });

    sitePage.property('viewportSize', {width: 800, height: 600}).then(function () {
    });

    var requestSuccess = false;
    var retry = 0;

    do {
        if (retry > retryLimit) {
            logger.error(`phantom retry out of limit, url: ${option.url}`);
            await phInstance.exit();
            return 'crawl failed';
        }
        if (retry !== 0 && retry <= retryLimit) {
            logger.debug(`phantom request retry: ${retry}`);
        }

        try {
            const status = await sitePage.open(options.url);
            let expectedCode = options.expectedCode || 200;

            if (status != expectedCode) {
                logger.error(`phantom request to ${url},returned err code of ${expectedCode}`);
                retry++;
                requestSuccess = false;
            }
            requestSuccess = true;
        } catch (err) {
            logger.fatal(`phantom request to ${url},occur err message is  ${err.toString()}`);
            retry++;
            requestSuccess = false;
        }

    } while (!requestSuccess);


    const html = await sitePage.property('content');


    await phInstance.exit();

    return html;
}





